'use strict';
const { Service } = require('egg');
class BaseService extends Service {
  constructor(ctx, modelName) {
    super(ctx);
    this.modelName = modelName;
  }

  getInclude() {
    return [];
  }
  getPageOrder() {
    return [
      [
        'id',
        'DESC'
      ]
    ]
  }
  getListOrder() {
    return [
      [
        'id',
        'DESC'
      ]
    ]
  }
  getPageOptions(page, pageSize) {
    return {
      offset: pageSize * (page - 1),
      limit: pageSize,
      order: this.getPageOrder(),
      include: this.getInclude(),
    };
  }

  async getPage(where, page, pageSize) {
    const options = this.getPageOptions(page, pageSize);
    return await this.ctx.model[this.modelName].findAndCountAll({
      where,
      ...options,
    });
  }

  async allList(where) {
    return this.ctx.model[this.modelName].findAll({
      where,
      order: this.getListOrder(),
      include: this.getInclude(),
    });
  }

  async findOne(id) {
    return await this.ctx.model[this.modelName].findOne({
      where: { id },
      include: this.getInclude(),
    });
  }

  async create(data) {
    delete data.id;
    return this.ctx.model[this.modelName].create(data);
  }

  async update(id, data) {
    return await this.ctx.model[this.modelName].update(data, {
      where: { id }
    });
  }

  async deleteById(id) {
    return await this.ctx.model[this.modelName].destroy({
      where: { id }
    });
  }
}

module.exports = BaseService;
